import {
  Component,
  OnInit,
  AfterViewInit,
  AfterViewChecked
} from "@angular/core";
import {
  trigger,
  animate,
  transition,
  state,
  style
} from "@angular/animations";
import { BroadcastService, BROADCAST_ACTION, BROADCAST_TYPE, BROADCAST_CLASSIC_PAYLOAD } from "broadcast";
import { Router, ActivatedRoute, RoutesRecognized } from "@angular/router";
import { Subject } from "rxjs/Subject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Subscription } from "rxjs/Subscription";
import { Observable } from "rxjs/Observable";
import { ConnectableObservable } from "rxjs/Observable/ConnectableObservable";
import { CmHttp } from "./../http-module/http.service";
import { getStockType, TOGGLE_STATE, getStockTypeThree, STOCK_TYPE } from "utils";
import { SummaryAssistantService } from "summary-assistant";
import { SocketService, BROADCAST_EVENT } from "socket";
import { BASEURL, STOCKURL } from "shared";
import { WatchlistMiniService } from "watchlist-mini";
import { ZytgSwitcher } from "stock";
import { UserService } from "user";


const getParams = symbols => {
  return symbols.reduce((str, symbol) => `${str}symbol=${symbol}&`, "?");
};

@Component({
  selector: "stock",
  templateUrl: "stock.component.html",
  styleUrls: ["stock.component.less"],
  animations: [
    trigger("expandable", [
      state(TOGGLE_STATE.EXPANDED, style({
        width: "*"
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
        width: "0",
        display: "none"
      })),
      transition(TOGGLE_STATE.COLLAPSED + " <=> " + TOGGLE_STATE.EXPANDED, animate("200ms"))
    ]),
    trigger("bottom", [
      state(TOGGLE_STATE.EXPANDED, style({
        height: "200px"
      })),
      state(TOGGLE_STATE.COLLAPSED, style({
        height: "30px"
      })),
      transition(TOGGLE_STATE.COLLAPSED + " <=> " + TOGGLE_STATE.EXPANDED, animate("200ms"))
    ]),
  ]
})
export class StockComponent implements OnInit {
  quoteToggle = new Subject();
  quoteDetailSource: ConnectableObservable<any>;
  // quoteDetailSource = new Subject();
  // quoteDetailSource = new ReplaySubject(1);
  indexSource = new ReplaySubject(1);
  blockSource;
  currentTab: string = "chart";
  stockParams;  // Observable
  stockSub = new Subject();
  isF10Source;
  currentSymbol;
  defaultStock: string = "000001.SS";
  getStockType = getStockType;
  isStock = true;
  outlookState = {
    all: true,
    watchlist: TOGGLE_STATE.EXPANDED,
    detail: TOGGLE_STATE.EXPANDED,
    bottom: TOGGLE_STATE.COLLAPSED
  };
  oldBottomState;
  placeSource = Observable.of("stock");
  access_level: string[];
  accessLevelSubscription: Subscription;
  // 众赢投顾新增指标
  zytgSwitchersList = [
    {
      text: "强势调整",
      key: "QSTZ",
      isMain: true,
      selected: false,
      isShow: false
    },
    {
      text: "超跌反弹",
      key: "CDFT",
      isMain: true,
      selected: false,
      isShow: false
    },
    {
      text: "猛虎出笼",
      key: "MHCL",
      isMain: true,
      selected: false,
      isShow: false
    },
    {
      text: "夹板",
      key: "JB",
      isMain: true,
      selected: false,
      isShow: false
    },
    {
      text: "股价活跃度",
      key: "GJHY",
      selected: false,
      isShow: false
    },
    {
      text: "量能活跃度",
      key: "LNHY",
      selected: false,
      isShow: false
//    },
//    {
//      text: "双神拍门",
//      key: "QSTZ",
//      selected: false
//    },
//    {
//      text: "梅开二度",
//      key: "QSTZ",
//      selected: false
    }
  ];

  tabList = [
    {
      text: "K线分析",
      url: "/chart",
      key: "$chart"
    },
    // {
    //   text: "成交明细",
    //   url: "/tick",
    //   key: "$tick"
    //   },
      {
        text: "基本面分析",
        url: "/f10",
        key: "$f10"
    }
  ];

  blockOptions = {
    responsive: {
      enabled: true,
    },
    parts: {
      emptyRow: false
    }
  };

  blockHeaders = {
    "headHeader": [
      {
        "label": "股票名称",
        "key": "name",
        "class": []
      },
      {
        "label": "现价",
        "key": "current",
        "withUpOrDown": true
      },
      {
        "label": "涨跌价",
        "key": "change_amount",
        "class": ["text-center"],
        "withUpOrDown": true
      },
      {
        "label": "涨跌幅",
        "key": "change_rate",
        "class": ["text-right"],
        "withUpOrDown": true,
        "withPercent": true
      }
    ]
  };
  indexHeaders = {
    "headHeader": [
      {
        "label": "指数名称",
        "key": "name",
        "class": []
      },
      {
        "label": "现价",
        "key": "current",
        "withUpOrDown": true,
        "upDownWith": "change_amount"
      },
      {
        "label": "涨跌价",
        "key": "change_amount",
        "class": ["text-center"],
        "withUpOrDown": true
      },
      {
        "label": "涨跌幅",
        "key": "change_rate",
        "class": ["text-right"],
        "withUpOrDown": true,
        "withPercent": true,
      }
    ]
  };

  historyGroup;
  historySubscription: Subscription;
  wlGroups;
  groupsDataSubscription: Subscription;

  constructor(
    private broadcast: BroadcastService,
    private http: CmHttp,
    private router: ActivatedRoute,
    private $router: Router,
    private summaryAssistant: SummaryAssistantService,
    private socket: SocketService,
    private wls: WatchlistMiniService,
    private userService: UserService
  ) { 
    this.accessLevelSubscription = userService.accessLevelSub.subscribe((data: Array<any>) => {
      this.access_level = data;
      // 初始化用户权限
      for(var i = 0; i < this.zytgSwitchersList.length; i ++ ) {
        if( this.isInArray(this.access_level,this.zytgSwitchersList[i].key)) {
          this.zytgSwitchersList[i].isShow = true;
        }
      } 
    });

    this.InitStock();
  }
  private InitStock() {
    this.wls.initStockStatus = true;
    this.wls.loadHistoryDetails();
    if ( window.location.pathname.length < 7 ) {
      // 接收历史自选股分组数据
      this.historySubscription = this.wls.initStockSub.subscribe((data: Array<any>) => {
        // console.debug("watchlist-mini history group data:", data);
        if ( this.historyGroup ) {
          this.historyGroup = data;
        }
        else {
          this.historyGroup = data;
          this.showStock();
        }
      });
    }
  }

  switchStock(stock) {
    this.stockSub.next(stock);
  }

  // 初始化开始
  ngOnInit() {
    let { http, summaryAssistant, socket } = this;
    // let timer = Observable.interval(5000);
    let timer = socket.broadcast.filter(e => e.event === BROADCAST_EVENT.RESET);

    this.quoteDetailSource = Observable.merge(timer, this.quoteToggle).scan((acc, value) => value["symbol"] ? value : acc)
      .filter(quote => quote["symbol"])
      // 这部分应该放在专门的外壳组件中
      // this.quoteToggle.switchMap(quote =>
      .switchMap(quote => {
        let reg = /\.XBHS$/g;
        if (reg.test(quote["symbol"])) {
          return Observable.zip(
            summaryAssistant.getSummaryBySymbol(quote["symbol"]),
            (detail) => Object.assign({}, detail)
          );
        } else {
          return Observable.zip(
            http.get(`${STOCKURL}/api/v2/sc/stocks/f10/${quote["symbol"]}/headlines`, {}, { errorBak: {}, cacheAge: http.CACHE_AGE.Instant}),
            summaryAssistant.getSummaryBySymbol(quote["symbol"]),
            (fData, detail) => Object.assign({}, detail, fData.data)
          );
        }
      }).publishReplay(10);
    this.quoteDetailSource.connect();
    this.quoteDetailSource.subscribe(res => {
      // 通过 detail.market 来判断分类
      this.isStock = getStockTypeThree(res) === STOCK_TYPE.STOCK;
      console.debug("Stock Type: ", this, this.isStock, res);
      // 推送消息
      // this.quoteDetailSource.next(res);

      // 设定历史浏览记录
      this.wls.updateHistorySymbols(res.symbol);
    });


    this.blockSource = this.quoteDetailSource
      .filter(stock => !this.isStock && stock && stock["symbol"])
      .switchMap(stock => {
        return this.http.get(`${BASEURL}/stock/block2symbols/${stock["symbol"]}`)
          .map(res => {
            return {
              id: res.type,
              dataUrl: `${BASEURL}/stock/summaries/dynpanel${getParams(res.symbols)}`,
            };
          });
      });

    this.indexSource.next({
      dataUrl: `${BASEURL}/stock/quotes/index`,
      id: Symbol()
    });

    setTimeout(() => {
      this.getBottom();
    }, 500);

    this.setBottom();

    // 股票代码分发
    this.stockParams =
      this.router.params.
        filter(params => params["id"]).
        map(params => {
          this.wls.emptyOfSelectStockSub.next();
          this.currentSymbol = params["id"].toUpperCase();
          return { symbol: params["id"].toUpperCase().replace("_", ".") };
        }).publishReplay(1);
    this.stockParams.connect();
    this.stockParams.subscribe(this.quoteToggle);
    this.isF10Source = this.$router.events;
    // this.stockParams.subscribe(stock => this.isStock = getStockTypeThree(stock) === STOCK_TYPE.STOCK);
    // this.stockParams.subscribe(stock => console.debug("STOCK SOURCE: ", stock));
    // 响应浏览器宽度判断
    Observable.fromEvent(window, "resize")
      .debounceTime(100)
      .subscribe((event) => {
        this.zytgOnresize();
      });
  }
  // 初始化结束
  private isInArray(arr,value){
    let str = value.toLowerCase();
    for(let i = 0; i < arr.length; i++){
        if(str === arr[i]){
            return true;
        }
    }
    return false;
  }

  changeTabView(tab: string) {
    this.currentTab = tab;
  }

  // 展示个股的详情
  showQuoteDetail(quote) {
    console.debug("Quote Detail: ", quote);
    this.quoteToggle.next(quote);
  }

  handleTabClick(tab) {
    let base = "/stock/{{currentSymbol}}";
    if (this.outlookState.bottom === "EXPANDED") {
      document.getElementsByClassName("icon-down")[0].click();
    }
    // 基本面分析和K线分析切换后，k线图众赢投顾指标初始化
    if (tab !== "f10") {
      this.zytgSwitchersList.forEach(d => {
        d.selected = false;
      });
    }
    // this.isF10 = /f10/.test(window.location.href
  }

  ngAfterViewInit() {
    this.switchStock(this.defaultStock);
  }

  ngAfterViewChecked() {
    // 检查众赢投顾指标栏宽度是否能显示全部指标 
    this.zytgOnresize();
  }

  toggleState(stateName: string) {
    console.debug("Toggle State: ", stateName);
    if (!stateName || !this.outlookState || !this.outlookState[stateName]) return;
    this.outlookState[stateName] = this.outlookState[stateName] === TOGGLE_STATE.COLLAPSED ? TOGGLE_STATE.EXPANDED : TOGGLE_STATE.COLLAPSED;
    this.getBottom();
    this.judgeMax();
  }

  toggleToMax() {
    if (this.outlookState.all) {
      this.oldBottomState = this.outlookState.bottom;
      this.outlookState.watchlist = TOGGLE_STATE.COLLAPSED;
      this.outlookState.detail = TOGGLE_STATE.COLLAPSED;
      this.outlookState.bottom = TOGGLE_STATE.COLLAPSED;
      this.setBottom();
      this.outlookState.all = false;
    }else {
      this.outlookState.watchlist = TOGGLE_STATE.EXPANDED;
      this.outlookState.detail = TOGGLE_STATE.EXPANDED;
      this.outlookState.bottom = this.oldBottomState;
      this.setBottom();
      this.outlookState.all = true;
    }
    let that = this;
    setTimeout(() => {
      that.zytgOnresize();
    }, 400);
  }
  // 判断是否处于最大化状态
  judgeMax() {
    if (this.outlookState.watchlist === TOGGLE_STATE.COLLAPSED && this.outlookState.detail === TOGGLE_STATE.COLLAPSED && this.outlookState.bottom === TOGGLE_STATE.COLLAPSED) {
      this.outlookState.all = false;
    } else {
      this.outlookState.all = true;
    }
  }

  // 传递bottom-toggle的状态
  setBottom() {
    this.broadcast.broadcast.next({
      type: BROADCAST_CLASSIC_PAYLOAD.TOGGLE_BOTTOM,
      payload: this.outlookState.bottom
    });
  }

  // 获取Bottom-toggle状态
  getBottom() {
    this.broadcast.broadcast
      .filter(e => e.type === BROADCAST_CLASSIC_PAYLOAD.TOGGLE_BOTTOM)
      .subscribe(e => {
        console.debug("Socket Toggle: ", e);
        this.outlookState.bottom = e.payload;
        this.judgeMax();
      });
  }



  broadcastRender() {
    this.broadcast.broadcast.next({
      type: BROADCAST_TYPE.RENDER_CHAERT
    });
  }

  f10Test(e: RoutesRecognized | null) {
    if (!e) return false;
    return /f10/.test(e.url);
  }

  // 选择众赢投顾指标
  onClick(switcher: ZytgSwitcher) {
    if (!switcher.isShow){
      this.userService.setModal("openService");
      return false;
    }
    if (switcher.disabled) {
      this.userService.setModal("developing");
      return false;
    }
    if (switcher.selected === true) {
      switcher.selected = false;
    }else {
      switcher.selected = true;
    }
    this.setList();
  }

  // 设置已选众赢投顾指标list
  setList() {
    let list = [];
    let hasMainIndicator = false;
    this.zytgSwitchersList.forEach(element => {
      if (element.selected === true) {
        list.push(element.key);
        if (element.isMain ) {
          hasMainIndicator = true;    // 标识是否选中有zytg的主图指标
        }
      }
    });

    list && this.tempSelectDayKLineByDOM();
    let broader = this.broadcast;
    setTimeout( function () {
      // 通知kchart-switcher选中的众赢投顾指标
      broader.broadcast.next({
        type: BROADCAST_TYPE.TOGGLE_ZYTG_INDICATOR,
        payload: {list: list, hasMain: hasMainIndicator}
      });
    }, 100);
  }

  // 目前众赢投顾指标均为日K指标，设置K线为日K
  // 由于其tab-list组件的后期选中绑定能力未具备，暂时先用js直接操作dom，后期优化    to do...
  tempSelectDayKLineByDOM() {
    let node = document.querySelectorAll(".kchart-tabs");
    if (node[0] && node[0].children[0] && node[0].children[0].children) {
      let nodes = node[0].children[0].children;
      for (let i = 1 ; i < nodes.length; i++) {
        if (nodes[i].innerText.substring(0, 1) === "日") {
            nodes[i].children && nodes[i].children[0].click();
            break;
        }
      }
    }
  }

  private showStock() {
    if ( this.historyGroup.length < 1 ) {
      this.$router.navigate(["/stock/000001_SS"]);
    } else {
      this.$router.navigate(["/stock",this.historyGroup[0].symbol.replace(".", "_")]);
    }
  }

  onDblClick(quote) {
    this.$router.navigate([`/stock/${quote.symbol.replace(/\./, "_")}`]);
  }

  // 指标区域下拉菜单 
  private zytgOnresize(){
    let target = document.getElementById("zytgTarget");
    let dropdown = document.getElementById("dropdown") as HTMLElement;
    let fl = document.getElementsByClassName("zytg-li");
    let toggle = document.getElementsByClassName("target-toggle");
    let tc = document.getElementsByClassName("dropdown-li");
    if (target && dropdown && fl && toggle && tc) {
      let targetWidth = target.offsetWidth;
      let flsWidth = 0;
      if (toggle[0]) {
        toggle[0].style.display = "show";
      }
      for (let i = 0; i < fl.length; i++) {
        tc[i].style.display = "none";
        flsWidth = flsWidth + fl[i].offsetWidth + 2;
        if (flsWidth > targetWidth) {
          tc[i].style.display = "block";
        }
      }
      if (flsWidth > targetWidth) {
        toggle[0].style.display = "block";
      } else {
        toggle[0].style.display = "none";
        dropdown.style.display = "none";
      }
    }

  }

  // 下拉点击事件
  targetDropdown () {
    let dropdown = document.getElementById("dropdown") as HTMLElement;
    if (dropdown.style.display === "block") {
      dropdown.style.display = "none";
    } else {
      dropdown.style.display = "block";
    }
  }
}